/* eslint-disable consistent-return */
import React from 'react';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Input, Table, Select, message, Modal, Row, Divider } from 'antd';
import { connect } from 'dva';

const { Option } = Select;
const FormItem = Form.Item;
const { confirm } = Modal;

@connect(({ loading }) => ({
  loading: loading.models.suppliermaintenance,
}))
class BasicList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      dataSource: [],
      nowPage: 1,
      pageNum: 10,
      cmTotal: 10,
      suppId: null,
      taxerIdNoS: null,
      vatCoprNameS: null,
      taxerTypeList: [],
      selectedRowKeys: [],
      isAdd: true,
      modalVisible: false,
      newFlieList: [],
      oldFileList: [],
      vno: 1,
      isRequired: false,
    };
    this.columns = [
      {
        title: '增值税单位名称',
        dataIndex: 'vatCoprName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '发票类型',
        dataIndex: 'invTypeName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '纳税人识别号',
        dataIndex: 'taxerIdNo',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '开户行',
        dataIndex: 'openBank',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '银行账号',
        dataIndex: 'bankAcco',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '开票电话',
        dataIndex: 'invPhone',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '开票地址',
        dataIndex: 'invArea',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '备注',
        dataIndex: 'remark',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <span className="editable-row-operations">
            <a onClick={e => this.update(e, record.invId)}>修改</a>
            <Divider type="vertical" />
            <a onClick={e => this.delList(e, record)}>删除</a>
          </span>
        ),
      },
    ];
  }

  componentDidMount = () => {
    const { suppId, taxerTypeList, dispatch } = this.props;
    this.setState({ suppId, taxerTypeList });
    const { nowPage, pageNum } = this.state;
    // 增值税单位名称列表
    dispatch({
      type: 'suppliermaintenance/getvatCoprName',
      payload: { suppId },
      callback: res => {
        if (res.success) {
          // this.setState({ taxerNameList: res.data });
        } else {
          message.warning(`${res.message || '暂无数据！'}`);
        }
      },
    });
    dispatch({
      type: 'suppliermaintenance/getTaxerName',
      payload: { suppId },
      callback: res => {
        if (res.success) {
          // this.setState({ taxerIdNoList: res.data });
        } else {
          message.warning(`${res.message || '暂无数据！'}`);
        }
      },
    });
    this.getList(nowPage, pageNum);
  };

  // 获取列表数据
  getList = (nowPage, pageNum) => {
    const { suppId, dispatch } = this.props;
    const { taxerIdNoS, vatCoprNameS, taxerTypeList } = this.state;
    this.setState({ loading: true });
    const pageArg = {
      currentPage: nowPage,
      pageSize: pageNum,
      orderBy: ' INV_ID DESC',
    };
    const params = { suppId, taxerIdNo: taxerIdNoS, vatCoprName: vatCoprNameS, pageArg };
    dispatch({
      type: 'suppliermaintenance/getInvoiceList',
      payload: params,
      callback: res => {
        if (res.success) {
          const data = res.data.pageRecords;
          data.forEach(item => {
            const temp = item;
            temp.taxerType = this.matchDict(taxerTypeList, temp.taxerType);
            temp.remark = temp.remark ? temp.remark : '暂无';
          });
          this.setState({
            dataSource: res.data.pageRecords,
            cmTotal: res.data.totalCount,
            loading: false,
          });
        } else {
          this.setState({ loading: false, cmTotal: 0, dataSource: [] });
          message.warning(`${res.message || '暂无数据！'}`);
        }
      },
    });
  };

  // 匹配字典
  matchDict = (list, id) => {
    const dict = null;
    list.forEach(item => {
      if (String(item.itemCode) === String(id)) {
        return item.itemName;
      }
    });
    return dict;
  };

  // 查询列表
  searchList = e => {
    e.preventDefault();
    const { form } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      this.setState({
        taxerIdNoS: values.taxerIdNoS ? values.taxerIdNoS.label : null,
        vatCoprNameS: values.vatCoprNameS ? values.vatCoprNameS.label : null,
        nowPage: 1,
        pageNum: 10,
      });
      this.setState({ nowPage: 1, pageNum: 10 });
      setTimeout(() => {
        this.getList(1, 10);
      }, 0);
    });
  };

  // 重置查询
  resetSearch = e => {
    e.preventDefault();
    const { form } = this.props;
    form.resetFields();
    const getFields = form.getFieldsValue();
    Object.keys(getFields).forEach(key => {
      this.setState({ [key]: null, nowPage: 1, pageNum: 10 });
    });
    setTimeout(() => {
      this.getList(1, 10);
    }, 0);
  };

  // 删除数据
  delList = (e, record) => {
    e.preventDefault();
    const { dispatch } = this.props;
    const { selectedRowKeys } = this.state;
    const rowKeys = [];
    const rows = [];
    rowKeys.push(record.invId);
    rows.push(record);
    this.setState({ selectedRowKeys: rowKeys });
    confirm({
      title: '你确定要刪除此条发票信息吗？',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        this.setState({ loading: true });
        dispatch({
          type: 'suppliermaintenance/deleteInvoiceMul',
          payload: { list: rowKeys },
          callback: res => {
            this.setState({ loading: false });
            if (res.success) {
              const { cmTotal, nowPage, pageNum } = this.state;
              const selectedLen = selectedRowKeys.length;
              if (
                nowPage > 1 &&
                (Number(cmTotal % pageNum) === Number(selectedLen) ||
                  String(pageNum) === String(selectedLen))
              ) {
                this.getList(nowPage - 1, pageNum);
                this.setState({ nowPage: nowPage - 1 });
              } else {
                this.getList(nowPage, pageNum);
              }
              this.setState({ selectedRowKeys: [] });
              message.success('删除成功！');
            } else {
              message.warning(`${res.message || '删除失败！'}`);
            }
          },
        });
      },
      onCancel: () => {},
    });
  };

  // 新增数据
  add = () => {
    this.handleModalVisible(true, true);
    const { form } = this.props;
    form.resetFields();
  };

  // 修改数据
  update = (e, invId) => {
    e.preventDefault();
    const { suppId, dispatch, form } = this.props;
    const rowKeys = [];
    rowKeys.push(invId);
    this.setState({ selectedRowKeys: rowKeys, loading: true });
    if (suppId) {
      dispatch({
        type: 'suppliermaintenance/getInvoiceInfo',
        payload: { invId },
        callback: res => {
          // console.log('点击修改后台返回数据', res.data)
          this.setState({ loading: false, suppId });
          if (res.success && res.data) {
            this.setState({ vno: res.data.vno });
            this.handleModalVisible(true, false);
            const getFieldsList = form.getFieldsValue();
            Object.keys(res.data).forEach(key => {
              if (res.data[key]) {
                if (key === 'invType') {
                  res.data[key] = `${res.data[key]}`;
                  if (String(res.data[key]) === '1') {
                    this.setState({ isRequired: true });
                  }
                }
              }
            });
            Object.keys(getFieldsList).forEach(key => {
              if (res.data[key]) {
                if (key === 'invType') {
                  form.setFieldsValue({ [key]: { key: res.data[key] } });
                } else {
                  form.setFieldsValue({ [key]: res.data[key] });
                }
              }
            });
            if (res.data.invoiceAffixList && res.data.invoiceAffixList.length) {
              this.setState({ oldFileList: res.data.invoiceAffixList });
            }
          } else {
            message.warning(`${res.message || '暂无数据！'}`);
          }
        },
      });
    }
  };

  // 切换模态框：新增、修改
  handleModalVisible = (flag, isAdd) => {
    this.setState({
      modalVisible: !!flag,
      isAdd,
      newFlieList: [],
    });
  };

  // 取消关闭模态框
  cancelModal = () => {
    this.handleModalVisible(false, true);
    this.setState({ loading: false, selectedRowKeys: [] });
  };

  // 选择发票类型
  selectTaxerType = value => {
    if (String(value.key) === '1') {
      this.setState({ isRequired: true });
    } else {
      this.setState({ isRequired: false });
    }
  };

  // 移除文件
  removeFile = (file, listContFile) => {
    const newData = listContFile.filter(item => item.uid !== file.uid);
    this.setState({ newFlieList: newData });
  };

  // 删除页面素材文件
  delFile = (id, oldFileList) => {
    const newData = oldFileList.filter(item => item.custAffixId !== id);
    this.setState({ oldFileList: newData });
  };

  // 新增修改提交数据
  submitData = () => {
    const {
      isAdd,
      suppId,
      selectedRowKeys,
      nowPage,
      pageNum,
      oldFileList,
      newFlieList,
      vno,
    } = this.state;
    const { dispatch, form } = this.props;
    let submitData = {};
    const submitType = isAdd
      ? 'suppliermaintenance/insertInvoiceInfo'
      : 'suppliermaintenance/updateInvoiceInfo';
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const temp = values;
        delete temp.vatCoprNameS;
        delete temp.taxerIdNoS;
        delete temp.invoiceLicense;
        Object.keys(temp).forEach(key => {
          if (temp[key] && temp[key].key) {
            temp[key] = temp[key].key;
          } else {
            temp[key] = temp[key] ? temp[key] : '';
          }
        });
        delete temp.invoiceAffixList;
        if (oldFileList.length) {
          oldFileList.forEach(f => {
            const tem = f;
            delete tem.suppId;
            delete tem.affixType;
            delete tem.glInfoId;
          });
        }
        if (newFlieList.length) {
          newFlieList.forEach(f => {
            const tem = f;
            delete tem.uid;
          });
        }
        submitData = isAdd
          ? { suppId, ...temp }
          : { suppId, ...temp, invId: selectedRowKeys[0], vno };
        this.setState({ loading: true });
        dispatch({
          type: submitType,
          payload: submitData,
          callback: res => {
            this.setState({ loading: false, modalVisible: false });
            if (res.success) {
              message.success(`${res.message || (isAdd ? '新增成功！' : '修改成功！')}`);
              this.getList(nowPage, pageNum);
              this.setState({ selectedRowKeys: [] });
            } else {
              message.warning(`${res.message || (isAdd ? '新增失败！' : '修改失败！')}`);
            }
          },
        });
      }
    });
  };

  render() {
    const {
      loading,
      dataSource,
      selectedRowKeys,
      modalVisible,
      isAdd,
      taxerTypeList,
      isRequired,
      nowPage,
      pageNum,
      cmTotal,
    } = this.state;
    const { form } = this.props;
    const { getFieldDecorator } = form;
    // 表格配置：行选择
    const rowSelection = {
      selectedRowKeys,
      onChange: selectedRowKeys1 => {
        this.setState({ selectedRowKeys: selectedRowKeys1 });
      },
    };
    // 表格配置：分页器
    const pagination = {
      defaultCurrent: nowPage, // 默认当前页
      defaultPageSize: pageNum, // 默认单页条数
      current: nowPage, // 当前页
      pageSize: pageNum, // 单页条数
      total: cmTotal, // 数据总数
      showQuickJumper: true, // 跳转至某页
      showSizeChanger: true, // 是否可以改变 pageSize
      onChange: (page, pageSize) => {
        // 页码改变的回调
        this.setState({ nowPage: page, pageNum: pageSize });
        this.getList(page, pageSize);
      },
      onShowSizeChange: (current, size) => {
        // 单页条数变化的回调
        this.setState({ nowPage: current, pageNum: size });
        this.getList(current, size);
      },
      showTotal: total => {
        const totalPage = total < pagination.pageSize ? 1 : Math.ceil(total / pagination.pageSize);
        return `共 ${total} 条记录 第 ${nowPage} / ${totalPage}页`;
      },
    };
    // 模态框布局
    const formItemLayoutModal = {
      labelCol: { md: { span: 6 } },
      wrapperCol: { md: { span: 16, offset: 1 } },
    };
    // 模态框配置
    const modalConfig = {
      title: isAdd ? '新增发票信息' : '修改发票信息',
      visible: modalVisible,
      confirmLoading: loading,
      onOk: this.submitData,
      okText: '提交',
      onCancel: this.cancelModal,
    };
    // 发票类型
    const taxerTypeOL = taxerTypeList.map(options => (
      <Option key={options.itemCode}>{options.itemName}</Option>
    ));
    return (
      <div>
        <Row style={{ marginBottom: '20px' }}>
          <Button type="primary" style={{ marginRight: 20 }} onClick={this.add}>
            <PlusOutlined />
            新增
          </Button>
        </Row>
        <Table
          rowSelection={rowSelection}
          dataSource={dataSource}
          columns={this.columns}
          rowKey={record => record.invId}
          loading={loading}
          pagination={pagination}
        />
        <Modal {...modalConfig}>
          <Form layout="horizontal">
            <FormItem {...formItemLayoutModal} label="增值税单位名称">
              {getFieldDecorator('vatCoprName', {
                rules: [{ required: true, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength="100" />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="发票类型">
              {getFieldDecorator('invType', {
                rules: [{ required: true, message: '请选择' }],
              })(
                <Select
                  placeholder="请选择"
                  labelInValue
                  optionFilterProp="children"
                  onChange={value => this.selectTaxerType(value)}
                >
                  {taxerTypeOL}
                </Select>
              )}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="纳税人识别号">
              {getFieldDecorator('taxerIdNo', {
                rules: [
                  {
                    required: true,
                    message: '最大长度不超过18的数字与字母组合',
                    pattern: /^[A-Za-z0-9]{1,20}$/,
                  },
                ],
              })(<Input placeholder="请输入" maxLength="18" />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="开户行">
              {getFieldDecorator('openBank', {
                rules: [{ required: isRequired, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength="100" />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="银行账号">
              {getFieldDecorator('bankAcco', {
                rules: [
                  {
                    required: isRequired,
                    message: '最大长度不超过25位数字',
                    pattern: /^\d{1,25}$/,
                  },
                ],
              })(<Input placeholder="请输入" maxLength="25" />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="开票电话">
              {getFieldDecorator('invPhone', {
                rules: [
                  {
                    required: isRequired,
                    message: '固话或手机',
                    pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/,
                  },
                ],
              })(<Input placeholder="请输入" maxLength="12" />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="开票地址">
              {getFieldDecorator('invArea', {
                rules: [{ required: isRequired, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength="100" />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="备注">
              {getFieldDecorator('remark', {
                rules: [{ required: false, message: '请选择' }],
              })(<Input placeholder="请输入" maxLength="200" />)}
            </FormItem>
          </Form>
        </Modal>
      </div>
    );
  }
}
const ListSearchForm = Form.create()(BasicList);
export default ListSearchForm;
